package com.aldobucchi.range
{
	
	import flash.events.EventDispatcher;
	
	import com.aldobucchi.core.dependency.DependencyHelper;
	import com.aldobucchi.core.dependency.DependencySpec;
	import com.aldobucchi.range.RangeMatcherEvent;


	public class RangeMatcher extends EventDispatcher
	{

		
		private var dh:DependencyHelper;
		
		
		///////////////////////////////////////////////
		// matchedRange
		///////////////////////////////////////////////
		
		private var _matchedRange:Range;
		
		[Bindable(RangeMatcherEvent.MATCHED_RANGE_CHANGED)]
		public function get matchedRange( ):Range
		{
			return _matchedRange;		
		}
		
		
		
		///////////////////////////////////////////////
		// rangeSet
		///////////////////////////////////////////////
		
		private var rangeSetSpec:DependencySpec = new DependencySpec( "rangeSet", "rangeSetChanged" );
		[Bindable("rangeSetChanged")]
		public function get rangeSet( ):RangeSet
		{
			return dh.getDependencyValue( rangeSetSpec );
		}
		
		public function set rangeSet( v:RangeSet ):void
		{
			dh.setDependencyValue( rangeSetSpec, v );
		}
		
		

		///////////////////////////////////////////////
		// value
		///////////////////////////////////////////////

		private var valueSpec:DependencySpec = new DependencySpec( "value", "valueChanged" );
		[Bindable("valueChanged")]
		public function get value( ):Number
		{
			return dh.getDependencyValue( valueSpec );
		}
		
		public function set value( v:Number ):void
		{
			dh.setDependencyValue( valueSpec, v );
		}






		public function RangeMatcher( )
		{
			dh = new DependencyHelper( this, update );
		
		
		}



		private function update( ):void
		{

			// something changed: the value, the rangeset, etc...
			if ( rangeSet == null )
			{
				setNewRange( null );
			}
			else if ( isNaN( value ) )
			{
				setNewRange( null );
			}
			else
			{
				setNewRange( rangeSet.getFirstRangeContainingValue( value ) );
			}

		}
		
		
		
		private function setNewRange( range:Range ):void
		{
		
			if ( matchedRange == range )
				return;
				
			var event:RangeMatcherEvent = new RangeMatcherEvent( RangeMatcherEvent.MATCHED_RANGE_CHANGED, matchedRange, range );			
		
			_matchedRange = range;
			
			dispatchEvent( event );
		
		}
		
		

		
	}
	
}